<template>
  <div class="app-container home">
    <!-- 顶部标题栏 -->
    <div class="home-header">
      <h1 class="header-title">
        <i class="el-icon-home text-primary mr-2"></i>乐康养老管理系统
      </h1>
      <div class="header-version">v1.0.0</div>
    </div>

    <!-- 顶部统计卡片 -->
    <el-row :gutter="24" class="statistic-row mb-6">
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">在住老人</div>
            <i class="el-icon-user-solid stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number" v-loading="elderlyCountLoading">{{ elderlyCount }}</div>
            <div class="stat-desc">
              <span class="text-success"
                ><i class="el-icon-arrow-up"></i> 2.3%</span
              >
              <span class="ml-2">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">空闲床位</div>
            <i class="el-icon-bed stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number">14</div>
            <div class="stat-desc">
              <span class="text-danger"
                ><i class="el-icon-arrow-down"></i> 5.1%</span
              >
              <span class="ml-2">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">今日预约</div>
            <i class="el-icon-calendar stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number" v-loading="todayAppointmentsLoading">{{ todayAppointmentsCount }}</div>
            <div class="stat-desc">
              <span class="text-success"
                ><i class="el-icon-arrow-up"></i> 8.7%</span
              >
              <span class="ml-2">较昨日</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">待办任务</div>
            <i class="el-icon-tasks stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number" v-loading="todayTasksLoading">{{ todayTasksCount }}</div>
            <div class="stat-desc">
              <span class="text-warning"><i class="el-icon-minus"></i> 0%</span>
              <span class="ml-2">较昨日</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">本月订单</div>
            <i class="el-icon-shopping-cart stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number">156</div>
            <div class="stat-desc">
              <span class="text-success"
                ><i class="el-icon-arrow-up"></i> 12.4%</span
              >
              <span class="ml-2">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="3">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-card-header">
            <div class="stat-title">欠费老人</div>
            <i class="el-icon-money stat-icon"></i>
          </div>
          <div class="stat-card-content">
            <div class="stat-number text-danger">3</div>
            <div class="stat-desc">
              <span class="text-success"
                ><i class="el-icon-arrow-down"></i> 25%</span
              >
              <span class="ml-2">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核心业务区域 -->
    <el-row :gutter="24" class="main-content mb-6">
      <!-- 左侧区域 -->
      <el-col :sm="24" :lg="12">
        <!-- 系统介绍 -->
        <el-card class="intro-card mb-6" shadow="hover">
          <div class="intro-content">
            <h3 class="intro-title">系统简介</h3>
            <p class="intro-desc">
              乐康养老管理系统专注于为养老院提供全方位运营管理解决方案，涵盖老人入住、护理服务、财务管理、预约管理等核心业务流程。
              系统采用轻量化架构设计，支持多终端访问，帮助机构提升管理效率，保障服务质量，为老人提供更优质的养老服务体验。
            </p>
            <div class="intro-tags">
              <el-tag type="primary" effect="light">智能管理</el-tag>
              <el-tag type="success" effect="light">高效运营</el-tag>
              <el-tag type="info" effect="light">多端适配</el-tag>
              <el-tag type="warning" effect="light">安全可靠</el-tag>
            </div>
          </div>
        </el-card>

        <!-- 业务数据概览 -->
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header flex justify-between items-center">
              <span class="chart-title">业务数据概览</span>
              <div class="chart-date">2024年10月</div>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <div class="chart-wrapper">
                <canvas id="bedUsageChart"></canvas>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-wrapper">
                <canvas id="serviceTypeChart"></canvas>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧区域 -->
      <el-col :sm="24" :lg="12">
        <!-- 快捷操作 -->
        <el-card class="operation-card mb-6" shadow="hover">
          <template #header>
            <div class="operation-header">快捷操作</div>
          </template>
          <el-row :gutter="16" class="operation-buttons">
            <el-col
              :xs="6"
              :sm="4"
              :lg="3"
              v-for="(item, index) in operationItems"
              :key="index"
            >
              <div class="operation-btn" @click="handleNavigate(item.url)">
                <div class="btn-icon" :style="{ background: item.color }">
                  <i :class="['el-icon-' + item.icon]"></i>
                </div>
                <div class="btn-text">{{ item.name }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 待办事项 -->
        <el-card class="todo-card mb-6" shadow="hover">
          <template #header>
            <div class="todo-header flex justify-between items-center">
              <span class="todo-title">我的待办</span>
              <el-button
                type="text"
                size="small"
                class="todo-more"
                @click="handleNavigate('/xietong/pendingTasks')"
              >
                查看全部
              </el-button>
            </div>
          </template>
          <el-list class="todo-list" v-loading="todoLoading">
            <el-list-item
              v-for="(item, index) in todoList"
              :key="index"
              class="todo-item"
              @click="handleNavigate(item.url)"
            >
              <div class="todo-item-left">
                <el-badge :type="item.badgeType" class="todo-badge">{{
                  item.type
                }}</el-badge>
                <span class="todo-item-title">{{ item.title }}</span>
              </div>
              <span class="todo-item-time">{{ item.time }}</span>
            </el-list-item>
            <el-list-item v-if="!todoLoading && todoList.length === 0" class="todo-empty">
              <div class="empty-text">暂无待办任务</div>
            </el-list-item>
          </el-list>
        </el-card>

        <!-- 最近预约 -->
        <el-card class="appointment-card" shadow="hover">
          <template #header>
            <div class="appointment-header flex justify-between items-center">
              <span class="appointment-title">最近预约</span>
              <el-button
                type="text"
                size="small"
                class="appointment-more"
                @click="handleNavigate('/laifang/yuyue/registration')"
              >
                查看全部
              </el-button>
            </div>
          </template>
          <el-table
            :data="recentAppointments"
            border
            size="mini"
            class="appointment-table"
            v-loading="appointmentLoading"
          >
            <el-table-column
              prop="name"
              label="预约人"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column prop="type" label="类型" width="90" align="center">
              <template #default="scope">
                <el-tag
                  :type="scope.row.type === 'visit' ? 'info' : 'success'"
                  effect="dark"
                >
                  {{ scope.row.type === "visit" ? "探访" : "参观" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="elderlyName"
              label="关联老人"
              width="130"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.elderlyName || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="time"
              label="预约时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="110"
              align="center"
            >
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'pending' ? 'warning' : 'success'"
                  effect="dark"
                >
                  {{ scope.row.status === "pending" ? "待确认" : "已确认" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 空状态显示 -->
          <div v-if="!appointmentLoading && recentAppointments.length === 0" class="appointment-empty">
            <div class="empty-text">暂无预约记录</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部信息区域 -->
    <el-row :gutter="24" class="footer-content">
      <el-col :xs="24" :sm="12" :lg="8">
        <el-card class="footer-card" shadow="hover">
          <template #header>
            <div class="footer-card-header">养老院信息</div>
          </template>
          <div class="nursing-home-info">
            <div class="info-item">
              <i class="el-icon-map-marker text-primary mr-3"></i>
              <span class="info-label">地址：</span>
              <span class="info-value">北京市朝阳区健康路88号乐康养老院</span>
            </div>
            <div class="info-item">
              <i class="el-icon-phone text-primary mr-3"></i>
              <span class="info-label">联系电话：</span>
              <span class="info-value">010-88776655</span>
            </div>
            <div class="info-item">
              <i class="el-icon-bed text-primary mr-3"></i>
              <span class="info-label">总床位数：</span>
              <span class="info-value">100 张</span>
            </div>
            <div class="info-item">
              <i class="el-icon-user text-primary mr-3"></i>
              <span class="info-label">收住老人：</span>
              <span class="info-value">86 人</span>
            </div>
            <div class="info-item">
              <i class="el-icon-clock text-primary mr-3"></i>
              <span class="info-label">营业时间：</span>
              <span class="info-value">08:00-18:00（全年无休）</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="8">
        <el-card class="footer-card" shadow="hover">
          <template #header>
            <div class="footer-card-header">系统公告</div>
          </template>
          <el-timeline class="notice-timeline">
            <el-timeline-item
              v-for="(notice, index) in notices"
              :key="index"
              :color="index === 0 ? '#409eff' : '#67c23a'"
              line-type="dashed"
            >
              <template #timestamp>
                <span class="notice-time">{{ notice.time }}</span>
              </template>
              <div class="notice-content">
                <span class="notice-dot"></span>
                {{ notice.content }}
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8">
        <el-card class="footer-card" shadow="hover">
          <template #header>
            <div class="footer-card-header">快速导航</div>
          </template>
          <div class="quick-nav">
            <el-row :gutter="16">
              <el-col :span="8" v-for="(item, index) in navItems" :key="index">
                <div class="nav-item" @click="handleNavigate(item.url)">
                  <div class="nav-icon-wrapper">
                    <i :class="['el-icon-' + item.icon, 'nav-icon']"></i>
                  </div>
                  <div class="nav-name">{{ item.name }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 页脚 -->
    <div class="home-footer">
      <div class="footer-copyright">
        © 2024 乐康养老管理系统 - 专注养老机构数字化运营
      </div>
    </div>
  </div>
</template>

<script setup name="LekangHome">
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
// 引入 Chart.js（使用标准导入）
import { Chart } from "chart.js/auto";
// 引入待办任务API
import { listPendingTasks } from "@/api/le/pendingTasks";
// 引入预约登记API
import { listRegistration } from "@/api/le/registration";
// 引入老人API
import { listElderly } from "@/api/le/elderly";

// 路由实例
const router = useRouter();

// 获取待办任务数据
const getTodoList = async () => {
  try {
    todoLoading.value = true;
    const queryParams = {
      pageNum: 1,
      pageSize: 4, // 只显示4条数据
      status: 1, // 只显示待处理状态
      isHandle: 0, // 只显示未处理的
    };
    
    const response = await listPendingTasks(queryParams);
    
    if (response.code === 200) {
      // 根据创建时间降序排序，只取前4条
      const sortedData = response.rows
        .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        .slice(0, 4);
      
      // 转换数据格式以适配模板
      todoList.value = sortedData.map(item => ({
        id: item.id,
        title: item.title,
        type: getTaskTypeLabel(item.type),
        time: formatTime(item.createTime),
        url: getTaskUrl(item.type, item.id),
        badgeType: getTaskBadgeType(item.type),
        status: item.status,
        isHandle: item.isHandle
      }));
    } else {
      console.error('获取待办任务失败:', response.msg);
      todoList.value = [];
    }
  } catch (error) {
    console.error('获取待办任务异常:', error);
    todoList.value = [];
  } finally {
    todoLoading.value = false;
  }
};

// 获取任务类型标签
const getTaskTypeLabel = (type) => {
  const typeMap = {
    1: '退住',
    2: '请假', 
    3: '入住'
  };
  return typeMap[type] || '未知';
};

// 获取任务徽章类型
const getTaskBadgeType = (type) => {
  const badgeMap = {
    1: 'warning',  // 退住
    2: 'success',  // 请假
    3: 'primary'   // 入住
  };
  return badgeMap[type] || 'info';
};

// 获取任务跳转URL
const getTaskUrl = (type, taskId) => {
  const urlMap = {
    1: '/xietong/pendingTasks',  // 退住
    2: '/xietong/pendingTasks',  // 请假
    3: '/xietong/pendingTasks'   // 入住
  };
  return urlMap[type] || '/xietong/pendingTasks';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 获取今天的日期字符串 (YYYY-MM-DD)
const getTodayString = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 检查日期是否为今天
const isToday = (dateString) => {
  if (!dateString) return false;
  const today = getTodayString();
  // 处理不同的日期格式
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate === today;
};

// 获取老人信息
const getElderlyInfo = async (elderlyId) => {
  try {
    if (!elderlyId) return null;
    
    const elderlyResponse = await listElderly({
      pageNum: 1,
      pageSize: 1000, // 获取所有老人数据
    });
    
    if (elderlyResponse.code === 200) {
      // 根据elderlyId查找对应的老人信息
      const elderly = elderlyResponse.rows.find(item => item.id == elderlyId);
      return elderly;
    }
    return null;
  } catch (error) {
    console.error('获取老人信息失败:', error);
    return null;
  }
};

// 获取在住老人总数
const getElderlyCount = async () => {
  try {
    elderlyCountLoading.value = true;
    
    const elderlyResponse = await listElderly({
      pageNum: 1,
      pageSize: 1000, // 获取所有老人数据
    });
    
    console.log('获取老人总数API响应:', elderlyResponse);
    
    if (elderlyResponse.code === 200) {
      // 直接使用API返回的total字段作为在住老人数量
      elderlyCount.value = elderlyResponse.total || 0;
      console.log('在住老人总数:', elderlyCount.value);
      console.log('所有老人数据:', elderlyResponse.rows);
    } else {
      console.error('获取老人总数失败:', elderlyResponse.msg);
      elderlyCount.value = 0;
    }
  } catch (error) {
    console.error('获取老人总数异常:', error);
    elderlyCount.value = 0;
  } finally {
    elderlyCountLoading.value = false;
  }
};

// 获取今日预约总数
const getTodayAppointmentsCount = async () => {
  try {
    todayAppointmentsLoading.value = true;
    
    const appointmentResponse = await listRegistration({
      pageNum: 1,
      pageSize: 1000, // 获取所有预约数据
    });
    
    console.log('获取今日预约总数API响应:', appointmentResponse);
    
    if (appointmentResponse.code === 200) {
      // 过滤出今天的预约
      const todayAppointments = appointmentResponse.rows.filter(item => 
        isToday(item.appointmentTime)
      );
      
      todayAppointmentsCount.value = todayAppointments.length;
      console.log('今日预约总数:', todayAppointmentsCount.value);
      console.log('今日预约数据:', todayAppointments);
    } else {
      console.error('获取今日预约总数失败:', appointmentResponse.msg);
      todayAppointmentsCount.value = 0;
    }
  } catch (error) {
    console.error('获取今日预约总数异常:', error);
    todayAppointmentsCount.value = 0;
  } finally {
    todayAppointmentsLoading.value = false;
  }
};

// 获取今日待办任务总数
const getTodayTasksCount = async () => {
  try {
    todayTasksLoading.value = true;
    
    const tasksResponse = await listPendingTasks({
      pageNum: 1,
      pageSize: 1000, // 获取所有待办任务数据
    });
    
    console.log('获取今日待办任务总数API响应:', tasksResponse);
    
    if (tasksResponse.code === 200) {
      // 过滤出今天创建的待办任务
      const todayTasks = tasksResponse.rows.filter(item => 
        isToday(item.createTime)
      );
      
      todayTasksCount.value = todayTasks.length;
      console.log('今日待办任务总数:', todayTasksCount.value);
      console.log('今日待办任务数据:', todayTasks);
    } else {
      console.error('获取今日待办任务总数失败:', tasksResponse.msg);
      todayTasksCount.value = 0;
    }
  } catch (error) {
    console.error('获取今日待办任务总数异常:', error);
    todayTasksCount.value = 0;
  } finally {
    todayTasksLoading.value = false;
  }
};

// 获取最近预约数据
const getRecentAppointments = async () => {
  try {
    appointmentLoading.value = true;
    const queryParams = {
      pageNum: 1,
      pageSize: 4, // 只显示4条数据
      // 移除status筛选，获取所有状态的预约
    };
    
    console.log('获取最近预约数据，查询参数:', queryParams);
    const response = await listRegistration(queryParams);
    console.log('预约API响应:', response);
    
    if (response.code === 200) {
      console.log('预约数据原始结果:', response.rows);
      // 根据预约时间降序排序，只取前4条
      const sortedData = response.rows
        .sort((a, b) => new Date(b.appointmentTime) - new Date(a.appointmentTime))
        .slice(0, 4);
      
      console.log('排序后的预约数据:', sortedData);
      
      // 转换数据格式以适配模板，并获取老人信息
      const appointmentPromises = sortedData.map(async (item) => {
        let elderlyName = '';
        if (item.elderlyId) {
          const elderlyInfo = await getElderlyInfo(item.elderlyId);
          elderlyName = elderlyInfo ? elderlyInfo.name || elderlyInfo.elderlyName || '' : '';
        }
        
        return {
          id: item.id,
          name: item.applicantName,
          type: item.appointmentType === 1 ? 'visit' : 'tour',
          elderlyName: elderlyName,
          elderlyId: item.elderlyId,
          time: formatTime(item.appointmentTime),
          status: item.status === '0' ? 'pending' : 'confirmed',
          phone: item.phone,
          appointmentType: item.appointmentType
        };
      });
      
      // 等待所有老人信息查询完成
      recentAppointments.value = await Promise.all(appointmentPromises);
      
      console.log('转换后的预约数据（包含老人信息）:', recentAppointments.value);
    } else {
      console.error('获取最近预约失败:', response.msg);
      recentAppointments.value = [];
    }
  } catch (error) {
    console.error('获取最近预约异常:', error);
    recentAppointments.value = [];
  } finally {
    appointmentLoading.value = false;
  }
};

// 快捷操作按钮配置（静态数据）
const operationItems = ref([
  { name: "来访登记", icon: "edit", color: "#409eff", url: "/visit/register" },
  {
    name: "办理入住",
    icon: "user-plus",
    color: "#67c23a",
    url: "/checkIn/apply",
  },
  {
    name: "护理任务",
    icon: "calendar-check",
    color: "#e6a23c",
    url: "/service/task",
  },
  {
    name: "生成账单",
    icon: "document",
    color: "#909399",
    url: "/finance/bill",
  },
  {
    name: "老人管理",
    icon: "user-solid",
    color: "#f56c6c",
    url: "/customer/elderly",
  },
  { name: "床位管理", icon: "bed", color: "#722ed1", url: "/checkIn/bed" },
  {
    name: "合同管理",
    icon: "file-text",
    color: "#13c2c2",
    url: "/living/contract",
  },
  {
    name: "财务统计",
    icon: "pie-chart",
    color: "#ff7a45",
    url: "/finance/statistic",
  },
]);

// 待办列表（动态数据）
const todoList = ref([]);
const todoLoading = ref(false);

// 最近预约（动态数据）
const recentAppointments = ref([]);
const appointmentLoading = ref(false);

// 在住老人统计数据
const elderlyCount = ref(0);
const elderlyCountLoading = ref(false);

// 今日预约统计数据
const todayAppointmentsCount = ref(0);
const todayAppointmentsLoading = ref(false);

// 今日待办任务统计数据
const todayTasksCount = ref(0);
const todayTasksLoading = ref(false);

// 系统公告（静态数据）
const notices = ref([
  {
    time: "2024-10-10",
    content: "10月15日将进行消防设施检查，请各部门做好准备工作",
  },
  {
    time: "2024-10-08",
    content: "新增护理等级标准已发布，请护理部组织全员学习",
  },
  {
    time: "2024-10-01",
    content: "国庆节期间探访时间调整为9:00-16:00，请注意通知家属",
  },
  {
    time: "2024-09-28",
    content: "10月起将启用新的财务结算系统，请财务人员提前熟悉操作",
  },
]);

// 快速导航（静态数据）
const navItems = ref([
  { name: "老人管理", icon: "user-solid", url: "/customer/elderly" },
  { name: "护理任务", icon: "calendar-check", url: "/service/task" },
  { name: "床位管理", icon: "bed", url: "/checkIn/bed" },
  { name: "财务账单", icon: "money", url: "/finance/bill" },
  { name: "预约管理", icon: "ticket", url: "/visit/list" },
  { name: "合同管理", icon: "document", url: "/living/contract" },
]);

// 图表实例（用于销毁）
let bedUsageChart = null;
let serviceTypeChart = null;
// 路由映射表 - 将原有的URL映射到实际的路由路径
const routeMap = {
  // 快捷操作路由映射
  "/visit/register": "/laifang/yuyue/visitor",
  "/checkIn/apply": "/xietong/shenqing/ru/ruzhuXq",
  "/service/task": "/fuwu/reuwu/job1",
  "/finance/bill": "/caiwu/zhangdan/bill",
  "/customer/elderly": "/fuwu/reuwu/job",
  "/checkIn/bed": "/zaizhu/chuangwei/bedFang",
  "/living/contract": "/zaizhu/contract",
  "/finance/statistic": "/caiwu/zhangdan/bill",

  // 待办事项路由映射
  "/checkIn/approval": "/xietong/pendingTasks",
  "/checkOut/approval": "/xietong/pendingTasks",
  "/service/plan/approval": "/fuwu/reuwu/job1",
  "/finance/bill/confirm": "/caiwu/zhangdan/bill",

  // 快速导航路由映射
  "/customer/elderly": "/fuwu/reuwu/job",
  "/service/task": "/fuwu/reuwu/job1",
  "/checkIn/bed": "/zaizhu/chuangwei/bedFang",
  "/finance/bill": "/caiwu/zhangdan/bill",
  "/visit/list": "/laifang/yuyue/registration",
  "/living/contract": "/zaizhu/contract",
};

// 导航处理（仅跳转提示，无实际路由）
const handleNavigate = (path) => {
  try {
    // 查找映射后的实际路径，如果找不到则使用原路径
    const actualPath = routeMap[path] || path;
    router.push(actualPath);
  } catch (error) {
    console.error("路由跳转失败:", error);
    ElMessage({
      type: "error",
      message: `跳转失败: ${error.message}`,
    });
  }
};

// 初始化图表（静态数据渲染）
const initCharts = () => {
  // 销毁旧图表
  if (bedUsageChart) bedUsageChart.destroy();
  if (serviceTypeChart) serviceTypeChart.destroy();

  // 1. 床位使用情况图表（环形图）
  const bedCtx = document.getElementById("bedUsageChart");
  if (bedCtx) {
    // 创建 Canvas 2D 上下文（用于生成渐变）
    const bedCtx2D = bedCtx.getContext("2d");

    // 已使用床位：绿色渐变（从左上角到右下角）
    const usedGradient = bedCtx2D.createLinearGradient(0, 0, 200, 200);
    usedGradient.addColorStop(0, "#4a7c59"); // 渐变起点颜色
    usedGradient.addColorStop(1, "#6bb86b"); // 渐变终点颜色

    // 空闲床位：灰色渐变（从左上角到右下角）
    const freeGradient = bedCtx2D.createLinearGradient(0, 0, 200, 200);
    freeGradient.addColorStop(0, "#f0f2f5"); // 渐变起点颜色
    freeGradient.addColorStop(1, "#e5e6eb"); // 渐变终点颜色

    bedUsageChart = new Chart(bedCtx, {
      type: "doughnut",
      data: {
        labels: ["已使用床位", "空闲床位"],
        datasets: [
          {
            data: [86, 14],
            // 使用 Canvas 渐变（而非 CSS 渐变）
            backgroundColor: [usedGradient, freeGradient],
            borderColor: "#ffffff",
            borderWidth: 4,
            hoverOffset: 12,
            cutout: "70%",
          },
        ],
      },
      options: {
        // 保持原有的其他配置...
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: "bottom",
            labels: {
              padding: 20,
              font: { size: 13, weight: "500" },
              color: "#444",
              usePointStyle: true,
            },
          },
          title: {
            display: true,
            text: "床位使用情况",
            font: { size: 16, weight: "bold" },
            color: "#333",
            padding: { bottom: 20 },
          },
        },
      },
    });
  }

  // 2. 服务类型统计图表（柱状图）
  const serviceCtx = document.getElementById("serviceTypeChart");
  if (serviceCtx) {
    serviceTypeChart = new Chart(serviceCtx, {
      type: "bar",
      data: {
        labels: ["晨间护理", "餐食服务", "康复训练", "医疗协助", "清洁服务"],
        datasets: [
          {
            label: "本月服务次数",
            data: [320, 450, 180, 95, 280],
            backgroundColor: [
              "rgba(64, 158, 255, 0.8)",
              "rgba(103, 194, 58, 0.8)",
              "rgba(230, 162, 60, 0.8)",
              "rgba(245, 108, 108, 0.8)",
              "rgba(144, 147, 153, 0.8)",
            ],
            borderColor: [
              "rgba(64, 158, 255, 1)",
              "rgba(103, 194, 58, 1)",
              "rgba(230, 162, 60, 1)",
              "rgba(245, 108, 108, 1)",
              "rgba(144, 147, 153, 1)",
            ],
            borderWidth: 1,
            borderRadius: 8,
            borderSkipped: false,
            barPercentage: 0.6,
            categoryPercentage: 0.7,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false,
          },
          title: {
            display: true,
            text: "本月服务类型统计",
            font: {
              size: 16,
              weight: "bold",
            },
            color: "#333",
            padding: {
              bottom: 20,
            },
          },
          tooltip: {
            backgroundColor: "rgba(255, 255, 255, 0.95)",
            titleColor: "#333",
            bodyColor: "#666",
            borderColor: "#eee",
            borderWidth: 1,
            padding: 12,
            boxPadding: 6,
            callbacks: {
              label: function (context) {
                return `服务次数: ${context.raw} 次`;
              },
            },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              color: "rgba(0, 0, 0, 0.05)",
              drawBorder: false,
            },
            ticks: {
              color: "#666",
              font: {
                size: 12,
              },
              stepSize: 100,
              padding: 10,
            },
          },
          x: {
            grid: {
              display: false,
            },
            ticks: {
              color: "#444",
              font: {
                size: 13,
                weight: "500",
              },
              padding: 10,
            },
          },
        },
        animation: {
          duration: 1500,
          easing: "easeOutQuart",
        },
      },
    });
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initCharts();
  getTodoList(); // 调用获取待办任务数据
  getRecentAppointments(); // 调用获取最近预约数据
  getElderlyCount(); // 调用获取在住老人总数
  getTodayAppointmentsCount(); // 调用获取今日预约总数
  getTodayTasksCount(); // 调用获取今日待办任务总数
});

// 组件销毁时销毁图表（防止内存泄漏）
onUnmounted(() => {
  if (bedUsageChart) bedUsageChart.destroy();
  if (serviceTypeChart) serviceTypeChart.destroy();
});
</script>

<style scoped lang="scss">
// 全局样式 - 养老系统绿色主题
$primary-color: #4a7c59;
$success-color: #6bb86b;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$light-gray: #f5f7fa;
$dark-gray: #45b794;

.app-container {
  background-color: $light-gray;
  min-height: 100vh;
  padding: 20px;
}

// 顶部标题栏
.home-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  .header-title {
    font-size: 24px;
    font-weight: 600;
    color: $dark-gray;
    display: flex;
    align-items: center;
  }
  .header-version {
    font-size: 13px;
    color: $info-color;
    background-color: rgba(74, 124, 89, 0.1);
    padding: 4px 12px;
    border-radius: 20px;
  }
}

// 统计卡片样式
.statistic-row {
  .stat-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08) !important;
    }
    .stat-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.03);
      .stat-title {
        font-size: 14px;
        font-weight: 500;
        color: #666;
      }
      .stat-icon {
        font-size: 20px;
        color: $primary-color;
        opacity: 0.7;
      }
    }
    .stat-card-content {
      padding: 20px;
      .stat-number {
        font-size: 32px;
        font-weight: 700;
        color: $dark-gray;
        margin-bottom: 8px;
        line-height: 1.2;
      }
      .stat-desc {
        font-size: 12px;
        color: $info-color;
        display: flex;
        align-items: center;
      }
    }
  }
}

// 系统介绍卡片
.intro-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  .intro-content {
    padding: 24px;
    .intro-title {
      font-size: 18px;
      font-weight: 600;
      color: $dark-gray;
      margin-bottom: 12px;
      display: flex;
      align-items: center;
    }
    .intro-desc {
      font-size: 14px;
      color: #666;
      line-height: 1.7;
      margin-bottom: 16px;
      text-align: justify;
    }
    .intro-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      .el-tag {
        padding: 4px 12px;
        font-size: 12px;
      }
    }
  }
}

// 图表卡片
.chart-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  .chart-header {
    padding: 16px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);
    .chart-title {
      font-size: 16px;
      font-weight: 600;
      color: $dark-gray;
    }
    .chart-date {
      font-size: 13px;
      color: $info-color;
    }
  }
  .chart-wrapper {
    width: 100%;
    height: 300px;
    padding: 20px;
  }
}

// 快捷操作卡片
.operation-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  .operation-header {
    padding: 16px 20px;
    font-size: 16px;
    font-weight: 600;
    color: $dark-gray;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);
  }
  .operation-buttons {
    padding: 20px;
    .operation-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s ease;
      &:hover {
        transform: translateY(-3px);
      }
      .btn-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8px;
        i {
          font-size: 22px;
          color: #fff;
        }
      }
      .btn-text {
        font-size: 13px;
        color: #666;
        font-weight: 500;
      }
    }
  }
}

// 待办事项卡片
.todo-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  .todo-header {
    padding: 16px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);
    .todo-title {
      font-size: 16px;
      font-weight: 600;
      color: $dark-gray;
    }
    .todo-more {
      font-size: 13px;
      color: $primary-color;
    }
  }
  .todo-list {
    padding: 0 20px;
    .todo-item {
      padding: 16px 0;
      border-bottom: 1px solid rgba(0, 0, 0, 0.03);
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      transition: all 0.2s ease;
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        background-color: rgba(64, 158, 255, 0.03);
      }
      .todo-item-left {
        display: flex;
        align-items: center;
        .todo-badge {
          margin-right: 12px;
          font-size: 12px;
          padding: 2px 8px;
        }
        .todo-item-title {
          font-size: 14px;
          color: #444;
          max-width: 280px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .todo-item-time {
        font-size: 12px;
        color: $info-color;
      }
    }
  }
}

// 最近预约卡片
.appointment-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  .appointment-header {
    padding: 16px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);
    .appointment-title {
      font-size: 16px;
      font-weight: 600;
      color: $dark-gray;
    }
    .appointment-more {
      font-size: 13px;
      color: $primary-color;
    }
  }
  .appointment-table {
    border-collapse: separate;
    border-spacing: 0;
    thead {
      th {
        background-color: rgba(0, 0, 0, 0.02);
        color: #666;
        font-weight: 500;
        font-size: 13px;
        border-bottom: none;
      }
    }
    tbody {
      tr {
        transition: all 0.2s ease;
        &:hover {
          background-color: rgba(64, 158, 255, 0.03);
        }
      }
      td {
        color: #444;
        font-size: 13px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.03);
        &:last-child {
          border-right: none;
        }
      }
    }
  }
}

// 空状态样式
.todo-empty {
  padding: 20px 0;
  text-align: center;
  .empty-text {
    font-size: 14px;
    color: $info-color;
  }
}

.appointment-empty {
  padding: 20px 0;
  text-align: center;
  .empty-text {
    font-size: 14px;
    color: $info-color;
  }
}

// 底部卡片通用样式
.footer-content {
  .footer-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.06) !important;
    }
    .footer-card-header {
      padding: 16px 20px;
      font-size: 16px;
      font-weight: 600;
      color: $dark-gray;
      border-bottom: 1px solid rgba(0, 0, 0, 0.03);
    }
  }
}

// 养老院信息
.nursing-home-info {
  padding: 20px;
  .info-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;
    &:last-child {
      margin-bottom: 0;
    }
    .info-label {
      font-size: 13px;
      color: $info-color;
      width: 70px;
      flex-shrink: 0;
    }
    .info-value {
      font-size: 14px;
      color: #444;
      flex-grow: 1;
      word-break: break-all;
    }
    i {
      margin-top: 2px;
      font-size: 16px;
    }
  }
}

// 系统公告
.notice-timeline {
  padding: 20px;
  .el-timeline-item {
    padding-bottom: 16px;
    &:last-child {
      padding-bottom: 0;
    }
    .notice-time {
      font-size: 12px;
      color: $info-color;
      margin-bottom: 8px;
      display: inline-block;
    }
    .notice-content {
      font-size: 14px;
      color: #444;
      position: relative;
      padding-left: 16px;
      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 8px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: $primary-color;
      }
    }
  }
}

// 快速导航
.quick-nav {
  padding: 20px;
  .nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-3px);
    }
    .nav-icon-wrapper {
      width: 44px;
      height: 44px;
      border-radius: 50%;
      background-color: rgba(64, 158, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 8px;
      .nav-icon {
        font-size: 20px;
        color: $primary-color;
      }
    }
    .nav-name {
      font-size: 13px;
      color: #666;
      font-weight: 500;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

// 页脚
.home-footer {
  margin-top: 30px;
  text-align: center;
  .footer-copyright {
    font-size: 13px;
    color: $info-color;
    padding: 16px 0;
    border-top: 1px solid rgba(0, 0, 0, 0.03);
  }
}

// 工具类
.flex {
  display: flex;
}
.justify-between {
  justify-content: space-between;
}
.items-center {
  align-items: center;
}
.mr-2 {
  margin-right: 8px;
}
.mr-3 {
  margin-right: 12px;
}
.ml-2 {
  margin-left: 8px;
}
.mb-6 {
  margin-bottom: 24px;
}
.text-primary {
  color: $primary-color;
}
.text-success {
  color: $success-color;
}
.text-danger {
  color: $danger-color;
}
.text-warning {
  color: $warning-color;
}
.text-info {
  color: $info-color;
}
</style>
